package com.king.netty.websocket;

import com.king.netty.heartbeat.MyIdleStateServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author unidentifiable
 * @date 2021-04-03
 */
public class MyWebSocketServer {
    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程数组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 基于http协议，使用http的编码器和解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 分块写入处理程序
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http数据在传输过程中是分段，HttpObjectAggreagator可以将多个段聚合
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /*
                                WebSocketServerProtocolHandler
                                    1. 对应websocket, 它的数据是以帧（frame）形式传递
                                    2. 可以看到 WebSocketFrame 下面有六个子类
                                    3. 浏览器请求时 ws://localhost:7000/xxx 表示请求的uri
                                    4. 核心功能是将http协议升级为ws协议，保持长连接
                                    5. 通过 101状态码 进行转换
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            // 自定义Handler，处理业务逻辑
                            pipeline.addLast(new MyTextWebSocketFrameHandler());
                        }
                    });

            // 启动
            ChannelFuture channelFuture = bootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
